import sys
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
use_library('django', '0.96')
from os import environ
from models import *
import datetime
import random
import re

global ids
class HelloPage(webapp.RequestHandler,db.Model):
	global ids
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='user':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/admin")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		global user,usr 
		user = users.get_current_user()
		global ids 
		ids=""
		user = users.get_current_user()
		url = self.request.url
		flag=0
		for i in range(0,len(url),1):
			if(url[i]=='?'):
				i=i+1
				while(url[i]!='='):
					ids=ids+url[i]
					i=i+1
					flag=1
				break
		if flag==0:
			ids=self.request.get("ids")
		if user:
			self.response.out.write('Hello, '+user.nickname())
			self.response.out.write(ids)
			path = os.path.join(os.path.dirname(__file__),'notifications.html')
			self.response.out.write(template.render(path,{"ids":ids}))
			
		else:
		        self.redirect(users.create_login_url(self.request.uri))


	def validate_emailid(self,emailid):					#validating email ids
		if (re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", emailid)):
			return 1
		else:
			return 0


	def check_user(self,admno):						#checks if member to be added is in anyother team.
		global m
		m=""
		t1=db.GqlQuery("SELECT * FROM teamDetails")
		for i in t1:
			self.response.out.write("hello");
			
			mem=i.teammember.split(',')
			for j in mem:
				if admno==j:
					m='user hit!'
					self.response.out.write(m)
					return 0
		return 1


	def post(self):
		global ids
		user = users.get_current_user()
		u=user.email()
		email=self.request.get("emailadr")
		emailid=email.split(',')
		n=1
		f=0
		f2=0
		rest=""
		not_id=""
		frm_usrid=""
		global m
		m=""
		msg=[]
		check2=2
		dont_enter=0
		userDetails=db.GqlQuery("SELECT * FROM userDetails")
		for usr in userDetails:
			if (usr.email==u):
				sender=usr.username
				frm_usrid=usr.admissionnumber
				f2=0
				break
			else:
				f2=1


		if self.request.get("single")=="Continue":
			team=teamDetails(teammember=frm_usrid,projectids=ids)
			key=team.put()
			tid=key.id()
			team.teamid=str(tid)
			team.put()
			proj=db.GqlQuery("SELECT * FROM projectDetails")
			for i in proj:
				if i.projectid==ids:
					break
			i.teamid=str(tid)
			i.maxmembers=str(1)
			i.put()	
			m='Single user successfully added!'
			msg.append(m)
			self.response.out.write(ids)
			path2 = os.path.join(os.path.dirname(__file__),'notifications_msg.html')
			self.response.out.write(template.render(path2,{'msg':msg,'back':dont_enter,'ids':ids}))		#passing message frm 1st loop to template
			
		else:
			max_members=1
			for i in emailid:					#1st loop to extract email ids frm list
				a=i
				if(a!=""):
					check=self.validate_emailid(i)
					if(check==1):
						userDetails=db.GqlQuery("SELECT * FROM userDetails")
						for usr in userDetails:		#2nd loop to retrieve userdetails (usr id)
							if (usr.email==a):
								
								admno=usr.admissionnumber
								check2=self.check_user(admno)
								self.response.out.write("<br>"+str(check2)+"<br>");
						
								if check2==1:
									max_members=max_members+1
									rest=usr.admissionnumber+','+rest
									message="You have been added to the team of '%s'" %sender
									n=notificationDetails(notificationid=not_id,admissionnumber=usr.admissionnumber,notification=message)
									key=n.put()
									noteid=key.id()
									n.notificationid=str(noteid)
									n.put()
									m='Notifications sent to: '+i
									msg.append(m)
									f=emailid.index(a)
									
								elif check2==0:
									m=a+' has been already added!'
									msg.append(m)
									f=emailid.index(a)
									dont_enter=1
							else:
								not_found=emailid.index(a)
						if (f<emailid.index(a)):
							m='No Records found for: '+a
							msg.append(m)
							dont_enter=1
					else:
						m=i+' is not a valid email id!'
						msg.append(m)
						dont_enter=1

			if(rest!="" and dont_enter==0):
				team=teamDetails(teammember=rest+frm_usrid,projectids=ids)
				key=team.put()
				tid=key.id()
				team.teamid=str(tid)
				team.put()
				proj=db.GqlQuery("SELECT * FROM projectDetails")
				for i in proj:
					if i.projectid==ids:
						break
				i.teamid=str(tid)
				i.maxmembers=str(max_members)
				i.put()
			self.response.out.write(ids)
			path2 = os.path.join(os.path.dirname(__file__),'notifications_msg.html')
			self.response.out.write(template.render(path2,{'msg':msg,'back':dont_enter,'ids':ids}))		#passing message frm 1st loop to template


class SentPage(webapp.RequestHandler,db.Model):
	global ids
	def get(self):
		global ids
		self.redirect("/choice?%s=id" %ids)

application = webapp.WSGIApplication([('/notification', HelloPage),('/sent',SentPage)],debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
